from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from users.models import Student
from .models import ScorePrediction
from .services import prediction_service
import json


@method_decorator(csrf_exempt, name='dispatch')
class ScorePredictionView(View):
    """成绩预测API - 简单版本"""

    def post(self, request):
        try:
            # 解析JSON数据
            data = json.loads(request.body.decode('utf-8'))

            # 获取参数
            student_id = data.get('student_id')
            subject_id = data.get('subject_id')
            target_exam_date = data.get('target_exam_date')

            # 基础验证
            if not student_id:
                return JsonResponse({
                    'success': False,
                    'error': '缺少student_id参数'
                }, status=400)

            if not subject_id:
                return JsonResponse({
                    'success': False,
                    'error': '缺少subject_id参数'
                }, status=400)

            if not target_exam_date:
                return JsonResponse({
                    'success': False,
                    'error': '缺少target_exam_date参数'
                }, status=400)

            # 调用预测服务
            result = prediction_service.predict_student_score(
                student_id=student_id,
                subject_id=subject_id,
                target_exam_date=target_exam_date
            )

            # 返回结果
            return JsonResponse(result)

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'error': 'JSON格式错误'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': f'服务器错误: {str(e)}'
            }, status=500)

    def get(self, request):
        """GET请求示例（用于测试）"""
        return JsonResponse({
            'message': '成绩预测API',
            'usage': 'POST方法调用预测，参数: student_id, subject_id, target_exam_date',
            'example': {
                'student_id': '学生UUID',
                'subject_id': 1,
                'target_exam_date': '2024-12-20'
            }
        })


def score_prediction_history(request, student_id):
    """获取学生的预测历史"""
    try:
        student = get_object_or_404(Student, id=student_id)
        predictions = ScorePrediction.objects.filter(student=student).order_by('-prediction_date')

        prediction_list = []
        for pred in predictions:
            prediction_list.append({
                'id': pred.id,
                'subject': pred.subject.name,
                'predicted_score': pred.predicted_score,
                'actual_score': pred.actual_score,
                'prediction_date': pred.prediction_date.strftime('%Y-%m-%d'),
                'target_exam_date': pred.target_exam_date.strftime('%Y-%m-%d'),
                'status': pred.get_status_display(),
                'prediction_error': pred.prediction_error
            })

        return JsonResponse({
            'success': True,
            'student_name': student.name,
            'predictions': prediction_list
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)


def score_prediction_verify(request, prediction_id):
    """验证预测准确性 - 输入实际分数"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            actual_score = data.get('actual_score')

            if not actual_score:
                return JsonResponse({
                    'success': False,
                    'error': '缺少actual_score参数'
                }, status=400)

            prediction = get_object_or_404(ScorePrediction, id=prediction_id)
            prediction.actual_score = actual_score
            prediction.save()  # 这会自动计算预测误差和更新状态

            return JsonResponse({
                'success': True,
                'message': '预测验证成功',
                'prediction_error': prediction.prediction_error,
                'status': prediction.get_status_display()
            })

        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)

    else:
        return JsonResponse({
            'success': False,
            'error': '只支持POST方法'
        }, status=405)


def weakness_analysis(request, student_id):
    """学生薄弱点分析"""
    try:
        student = get_object_or_404(Student, id=student_id)

        # 这里可以调用你的薄弱点分析服务
        # 暂时返回模拟数据
        weakness_data = {
            'student_name': student.name,
            'analysis_date': '2024-01-01',
            'weak_areas': [
                {
                    'subject': '数学',
                    'knowledge_point': '函数极限',
                    'weakness_level': 'high',
                    'improvement_suggestions': ['重点练习极限计算', '理解极限定义']
                },
                {
                    'subject': '英语',
                    'knowledge_point': '阅读理解',
                    'weakness_level': 'medium',
                    'improvement_suggestions': ['增加阅读量', '学习阅读技巧']
                }
            ]
        }

        return JsonResponse({
            'success': True,
            'data': weakness_data
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)
